#
#
#
import bluetooth
import time
import RPi.GPIO as GPIO
from components.motor import Motor

motor = Motor()

##########蓝牙连接接收命令##################
server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)

port = 1
server_sock.bind(('', port))
server_sock.listen(1)

# 只有一个客户端可以连接上，并控制小车
# 小车进程不会退出，直到主动kill进程
while True:

    print('ready accept connection...')

    # 接受客户端连接
    client_sock, address = server_sock.accept()
    print('Accepted connection from ', address)

    while True:
        try:
            # 读取命令字符
            action = int(client_sock.recv(1024))
            print('received action [%s]' % action)

            # 控制小车执行命令
            if action == 1:       # 前进
                motor.action(Motor.GO)
            elif action == 2:     # 后退
                motor.action(Motor.BACK)
            elif action == 3:     # 左转
                motor.action(Motor.LEFT)
            elif action == 4:     # 右转
                motor.action(Motor.RIGHT)

            elif action == 5:     # 停止
                motor.action(Motor.STOP)
            else:                 # 未知命令，小车停止
                motor.action(Motor.STOP)
        except:

            # 遇到意外，小车停止，断开蓝牙连接
            print('except...')
            motor.action(Motor.STOP)
            break

        # finally:

    # 断开客户端连接
    client_sock.close()
    print('close connection from ', address)
